package main

import (
	"image/color"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"

	"gui"

	. "azlog"
)

type TUI struct {
	a       fyne.App
	w       fyne.Window
	content *fyne.Container

	toolbar   *widget.Toolbar
	left_tree *widget.Tree

	top_text    *canvas.Text
	left_text   *canvas.Text
	middle_text *canvas.Text
}

func (ui *TUI) initToolbar() {
	ui.toolbar = widget.NewToolbar(
		widget.NewToolbarAction(theme.DocumentCreateIcon(), func() {
			LOG_I("新建文档")
		}),
		widget.NewToolbarSeparator(),
		widget.NewToolbarAction(theme.ContentCutIcon(), func() {}),
		widget.NewToolbarAction(theme.ContentCopyIcon(), func() {}),
		widget.NewToolbarAction(theme.ContentPasteIcon(), func() {}),
		widget.NewToolbarSpacer(),
		widget.NewToolbarAction(theme.HelpIcon(), func() {
			LOG_I("显示帮助")
		}),
	)
}

func (ui *TUI) initLeftTree() {
	ui.left_tree = widget.NewTree(
		func(id widget.TreeNodeID) []widget.TreeNodeID {
			switch id {
			case "":
				return []widget.TreeNodeID{"a", "b", "c"}
			case "a":
				return []widget.TreeNodeID{"a1", "a2"}
			}
			return []string{}
		},
		func(id widget.TreeNodeID) bool {
			return id == "" || id == "a"
		},
		func(branch bool) fyne.CanvasObject {
			if branch {
				return widget.NewLabel("文件夹")
			} else {
				// return canvas.NewText("文件", color.Black)
				return widget.NewLabel("执行项")
			}
		},
		func(id widget.TreeNodeID, branch bool, o fyne.CanvasObject) {
			text := id
			if branch {
				text += " (分支)"
			}
			o.(*widget.Label).SetText(text)
			LOG_D("显示 %s", text)
		})

	ui.left_tree.OnSelected = func(id widget.TreeNodeID) {
		LOG_D("点击了 %s", id)
	}
}

func (ui *TUI) init() {
	ui.a = app.New()
	ui.w = ui.a.NewWindow("AzToolMgr-(测试版)")

	// ui.top_text = canvas.NewText("顶部", color.Black)
	ui.left_text = canvas.NewText("左侧", color.Black)
	ui.middle_text = canvas.NewText("内容", color.Black)

	ui.initToolbar()
	ui.initLeftTree()

	ui.content = container.NewBorder(ui.toolbar, nil, ui.left_tree, nil, ui.middle_text)
	ui.w.SetContent(ui.content)
	ui.w.Resize(fyne.NewSize(800, 600))
	ui.w.SetFixedSize(true)
}

func (ui *TUI) update() {
	ui.left_text.Text = "左侧"
	ui.middle_text.Text = "内容"
	ui.w.Canvas().Refresh(ui.left_text)
	ui.w.Canvas().Refresh(ui.middle_text)
}

func (ui *TUI) run() {
	ui.w.Show()
	ui.a.Run()
}

var g_ui TUI

func UiCreate() {
	LOG_I("UI created")

}

func UiInit() {
	LOG_I("UI initialized")
	g_ui.init()
}

func UiRun() {
	LOG_I("UI running")
	gui.ExceptionWindow("UI创建异常")
	g_ui.run()
}

func UiDone() {
	LOG_I("UI deinitialized")
}

func UiDestroy() {
	LOG_I("UI destroyed")
}
